<?php
/**
 * Created by phpStorm.
 * BuyUser: xl
 * Date: 2018/3/1
 * Time: 18:00
 */
namespace app\controllers;

use common\services\LogService;
use Yii;
use yii\web\Controller;
use yii\web\Response;
use common\widgets\Tool;
use yii\filters\VerbFilter;
use yii\filters\Cors;

class BaseController extends Controller {

    private $logid = '0';
    protected $controller_auth = '';
    protected $action_code = '';

    private $craftsman_key = ';[[]=-0987163%$##@&*())&^^%%^';

    public $enableCsrfValidation=false;

    public function behaviors()
    {
        $behaviors = [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [],
            ],
            'corsFilter' => [
                'class' => Cors::className(),
                'cors' => [
                    'Origin' => ['*'],
                    'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
                    'Access-Control-Request-Headers' => ['*'],
                    'Access-Control-Allow-Origin' => ['*'],
                    'Access-Control-Allow-Credentials' => true,
                    'Access-Control-Max-Age' => 86400,
                    'Access-Control-Expose-Headers' => [],
                ],
            ],
        ];
        if (Yii::$app->getRequest()->getMethod() !== 'OPTIONS') {
//            $behaviors['authenticator'] = [
//                'class' => HttpBearerAuth::className(),
//                'optional' => [
//                    'login',
//                    'signup'
//                ],
//            ];
        }

        return $behaviors;
    }
    public function init()
    {
        $token = Yii::$app->request->headers->get('x-auth-token');
        $craftsman_key = $this->craftsman_key;
        $pathinfo = Yii::$app->request->pathInfo;
        if($token != md5($craftsman_key.'/'.$pathinfo)){
            return Tool::returnJson([], 501, 'token 验证失败');
        }else{
            return Tool::returnJson([], 202, 'token 验证成功');
        }
        parent::init(); // TODO: Change the autogenerated stub
    }
//    public function init()
//    {
//        header("Origin:*");
//        header("Access-Control-Allow-Origin:*");
//        header("Access-Control-Allow-Credentialsgit :true");
//        header("Content-Type:application/json");
//        $response = \Yii::$app->response;
//        $response->format = 'raw';
//        $response->headers->add('Content-Type', 'application/json');
//
//        parent::init();
//
//    }

    /**
     * 加载错误action
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

//    public function beforeAction($action)
//    {
//        //token 验证
//        $request = Yii::$app->request->get();
//        $str = '';
//
//        $server = Yii::$app->request;
////        print_r($server);exit;
//
//        $user_id = Yii::$app->user->id;
//        $redis_user_id = $source = Yii::$app->redis->get($user_id);
//        //$redis_user_id = $source = Yii::$app->redis->del($user_id);
//        //判断登录状态
//        //Yii::$app->redis->ttl($user_id);
//        if(empty($redis_user_id))
//        {
//            echo Tool::returnJson([], 400, '用户需要登录');
//            exit;
//        }
//
////        $login_expire_time = Yii::$app->session['login_expire_time'];
////        if($login_expire_time < time())
////        {
////            echo Tool::returnJson([], 401, '登录已过期，请重新登录');
////            exit;
////        } else {
////            Yii::$app->session['login_expire_time'] = time() + Yii::$app->params['login_session_expire_time'];
////        }
//
//        Tool::xssFilter($_GET,true);
//        $this->enableCsrfValidation = false;
//
//        $controller_name = $action->controller->id;
//	    $action_name = $action->id;
//
////        var_dump(Yii::$app->buyuser);exit;
//	    if (array_key_exists($controller_name, Yii::$app->params['auth_config'])) {
//            //获取该控制器的权限配置
//            $this->controller_auth = Yii::$app->params['auth_config'][$controller_name];
//		    if (array_key_exists($action_name, $this->controller_auth)) {
//                //获取该方法的权限配置
//                $this->action_code = $this->controller_auth[$action_name];
//            }
//        }
//
//        $param = array(
//            'actionLeavePage'
//        );
//
//        $method = $action->actionMethod;
////        if (!in_array($method, $param) && Yii::$app->request->isPost) {
//            $this->logid = LogService::InputTeacherLog(Yii::$app->request);
////        }
//
//
//        return parent::beforeAction($action);
//    }
//
//    public function afterAction($action, $result)
//    {
//        $response=Yii::$app->response;
//        $response->format = Response::FORMAT_JSON;
//
//        $this->SaveLogs($action,$result);
//        Yii::$app->db->close();
//
//        return parent::afterAction($action, $result); // TODO: Change the autogenerated stub
//    }
//
//    /*
//     * 添加老师管理系统操作日志
//     */
//    private function SaveLogs($action,$result)
//    {
//        $method = $action->actionMethod;
//
//        $param = array(
//            'actionLeavePage'
//        );
//
////        if(!in_array($method, $param) && Yii::$app->request->isPost)
////        {
//            LogService::OutputTeacherLog($this->logid, $result);
////        }
//    }
}